package algorithm.leetcode

/**
 * 数组的度
 */
object ArrayDu {
    fun findShortSubArray(nums : IntArray) : Int{
        val tmp = mutableMapOf<Int, IntArray>()
        nums.forEachIndexed { index, num ->
            val exist = tmp[num]
            if(exist == null){
                //0 存放出现次数，1存放首次出现位置，2存放最后出现位置
                val ar = IntArray(3)
                ar[0] = 1
                ar[1] = index
                ar[2] = index
                tmp[num] = ar
            }else{
                exist[0] += 1
                exist[2] = index
            }
        }
        var max = 0
        var minlen = 0
        tmp.forEach { t, u ->
            if(u[0] > max){
                max = t
                minlen = u[2] - u[1] + 1
            }else if(u[0] == max){
                val len = u[2] - u[1] + 1
                if(minlen > len){
                    minlen = len
                }
            }
        }
        return minlen
    }
}

fun main(){
    val ar = intArrayOf(1,2,2,3,1)
    println(ArrayDu.findShortSubArray(ar))
}